package com.example.cardgame

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import android.provider.MediaStore
import android.text.Editable
import android.widget.Button
import android.widget.CheckBox
import android.widget.EditText
import android.widget.ImageView
import android.widget.RadioButton
import android.widget.RadioGroup
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import java.io.ByteArrayOutputStream
import android.util.Base64
import android.util.Log
import android.widget.ImageButton
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.view.menu.ActionMenuItem

class PersonInfomation : AppCompatActivity() {

    companion object {
        const val REQUEST_IMAGE_CAPTURE = 1
    }
    private var imageBitmap: Bitmap? = null // 用于存储拍照结果

    @SuppressLint("MissingInflatedId")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_person_infomation)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        //获取控件
        val save: Button = findViewById(R.id.save)
        val cancel: Button = findViewById(R.id.cancel)
        val name: EditText = findViewById(R.id.name)
        val stuNumber: EditText = findViewById(R.id.stuNumber)
        val phoneNumber: EditText = findViewById(R.id.phoneNumber)
        val email: EditText = findViewById(R.id.email)
        val radioGroup: RadioGroup = findViewById(R.id.radioGroup)
        val checkBox1: CheckBox = findViewById(R.id.checkBox)
        val checkBox2: CheckBox = findViewById(R.id.checkBox2)
        val checkBox3: CheckBox = findViewById(R.id.checkBox3)
        val checkBox4: CheckBox = findViewById(R.id.checkBox4)


        // 接收传递过来的参数
        val intent = getIntent()
        name.text = Editable.Factory.getInstance().newEditable(intent.getStringExtra(NAME))
        stuNumber.text = Editable.Factory.getInstance().newEditable(intent.getStringExtra(STU_NUMBER))
        phoneNumber.text = Editable.Factory.getInstance().newEditable(intent.getStringExtra(PHONE_NUMBER))
        email.text = Editable.Factory.getInstance().newEditable(intent.getStringExtra(EMAIL))
        //接收传递过来的性别给单选框
        val  gender = intent.getStringExtra(GENDER)
        if(gender=="男"){
            radioGroup.check(R.id.radioButton2)
        }else{
            radioGroup.check(R.id.radioButton3)
        }
        //接收传递过来的爱好String 传递给复选框
        val hobby = intent.getStringExtra(HOBBY)
        val hobbies = hobby?.split(", ")
        if (hobbies != null) {
            for (h in hobbies) {
                when (h) {
                    "旅游" -> checkBox1.isChecked = true
                    "阅读" -> checkBox2.isChecked = true
                    "游戏" -> checkBox3.isChecked = true
                    "购物" -> checkBox4.isChecked = true
                }
            }
        }

        //接收传过来的图片给图片框
        val encodedImage = intent.getStringExtra("image")
        if (encodedImage != null) { //检查图片是否为空
            val byteArray = Base64.decode(encodedImage, Base64.DEFAULT) //为空则解码图片
            val imageBitmap = byteArray?.size?.let { BitmapFactory.decodeByteArray(byteArray, 0, it) }  //将解码后的图片转换为Bitmap
            val imageView = findViewById<ImageView>(R.id.avatar)       //获取ImageView
            imageView.setImageBitmap(imageBitmap)   //显示图片
        } else {    //如果图片为空则显示默认图片
            val imageView = findViewById<ImageView>(R.id.avatar)
            imageView.setImageResource(R.drawable.avatar)
        }


        //保存按钮事件
        save.setOnClickListener {
            //将文本框中的内容传递给Home
            val intent = Intent()
            intent.putExtra(NAME, name.text.toString())
            intent.putExtra(STU_NUMBER, stuNumber.text.toString())
            intent.putExtra(PHONE_NUMBER, phoneNumber.text.toString())
            intent.putExtra(EMAIL, email.text.toString())
            //识别单选框中的性别转换为String形式传递给Home中的性别文本框
            val genderString = findViewById<RadioButton>(radioGroup.checkedRadioButtonId).text.toString()
            intent.putExtra(GENDER, genderString)

            //将复选选框中的内容以String形式传递给Home的爱好文本框
            val hobbies = ArrayList<String>()
            if (checkBox1.isChecked) hobbies.add("旅游")
            if (checkBox2.isChecked) hobbies.add("阅读")
            if (checkBox3.isChecked) hobbies.add("游戏")
            if (checkBox4.isChecked) hobbies.add("购物")

            //将爱好转换为String后传递给Home
            val hobbiesString = hobbies.joinToString(", ")
            intent.putExtra(HOBBY, hobbiesString)

            //将图片传递给Home
            imageBitmap?.let {//检查图片是否为空
                val byteArrayOutputStream = ByteArrayOutputStream()//创建一个新的字节数组输出流
                it.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream)//将图片压缩为PNG格式
                val byteArray = byteArrayOutputStream.toByteArray()//   将图片转换为字节数组
                val encodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT)//将字节数组编码为Base64字符串
                intent.putExtra("image", encodedImage)//将图片以字符串形式传递给Home
            }
            setResult(RESULT_OK, intent)
            //结束当前活动
            finish()
        }

        //取消按钮事件
        cancel.setOnClickListener {
            finish()
        }

        // 拍照按钮点击事件
        val button:ImageButton= findViewById(R.id.camera)
//        val launcher = registerForActivityResult(ActivityResultContracts.TakePicturePreview()) {
//            imageBitmap ->
//            val imageView = findViewById<ImageView>(R.id.avatar)
//            imageView.setImageBitmap(imageBitmap)
//        }
        button.setOnClickListener {
            dispatchTakePictureIntent()//调用拍照方法
//            launcher.launch(null)
        }

    }

    // 拍照逻辑
    private fun dispatchTakePictureIntent() {

        val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)//创建拍照意图
        if (intent.resolveActivity(packageManager) != null) {    //检查是否有相机应用
            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE)    //启动拍照活动
        }else {
            Log.e("FourthActivity", "No camera app found to handle the intent") // 添加日志
        }
    }

    // 拍照后的回调
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {  //检查请求码和结果码
            imageBitmap = data?.extras?.get("data") as Bitmap   //获取拍照结果
            val imageView = findViewById<ImageView>(R.id.avatar)    //获取ImageView
            imageView.setImageBitmap(imageBitmap)   //显示拍照结果
        }
    }

}